import { Byte } from '../../api/io/Byte';
import { ArenaRecordPlayer } from './ArenaRecordPlayer';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**竞技场历史记录属性枚举*/
export const enum E_ArenaRecord {
	/**战斗id*/
	BATTLE_ID = 0,
	/**挑战时间*/
	TIME = 1,
	/**战斗类型（玩家，关卡，机器人等）*/
	ENEMY_TYPE = 2,
	/**胜利方*/
	WIN_CAMP = 3,
	/**左边玩家*/
	LEFT_PLAYER = 4,
	/**右边玩家*/
	RIGHT_PLAYER = 5,
	/**枚举数量*/
	EnumCount = 6
}


/**竞技场历史记录*/
export class ArenaRecord {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ARENA_RECORD_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ARENA_RECORD_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ArenaRecord[] = [];

	/**创建入口*/
	public static create(json?: string): ArenaRecord {
		const c = this.POOL.pop() || new ArenaRecord();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**战斗id (long)*/
	protected _battleId: number;
	/**挑战时间 (long)*/
	protected _time: number;
	/**战斗类型（玩家，关卡，机器人等） (uint8)*/
	protected _enemyType: number;
	/**胜利方 (uint8)*/
	protected _winCamp: number;
	/**左边玩家*/
	protected _leftPlayer: ArenaRecordPlayer = null;
	/**右边玩家*/
	protected _rightPlayer: ArenaRecordPlayer = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ArenaRecord.POOL.indexOf(this) === -1) {
			ArenaRecord.POOL.push(this);
		}
	}

	/**战斗id*/
	public get battleId() {
		return this._battleId;
	}


	/**战斗id*/
	public set battleId(v: number) {
		this._battleId = v;
	}


	/**挑战时间*/
	public get time() {
		return this._time;
	}


	/**挑战时间*/
	public set time(v: number) {
		this._time = v;
	}


	/**战斗类型（玩家，关卡，机器人等）*/
	public get enemyType() {
		return this._enemyType;
	}


	/**战斗类型（玩家，关卡，机器人等）*/
	public set enemyType(v: number) {
		this._enemyType = v;
	}


	/**胜利方*/
	public get winCamp() {
		return this._winCamp;
	}


	/**胜利方*/
	public set winCamp(v: number) {
		this._winCamp = v;
	}


	/**左边玩家*/
	public get leftPlayer() {
		return this._leftPlayer;
	}


	/**右边玩家*/
	public get rightPlayer() {
		return this._rightPlayer;
	}



	/**通过枚举获取值*/
	public getV(k: E_ArenaRecord): any {
		switch (k) {
			case E_ArenaRecord.BATTLE_ID: return this._battleId;
			case E_ArenaRecord.TIME: return this._time;
			case E_ArenaRecord.ENEMY_TYPE: return this._enemyType;
			case E_ArenaRecord.WIN_CAMP: return this._winCamp;
			case E_ArenaRecord.LEFT_PLAYER: return this._leftPlayer;
			case E_ArenaRecord.RIGHT_PLAYER: return this._rightPlayer;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ArenaRecord, v: any): void {
		switch (k) {
			case E_ArenaRecord.BATTLE_ID: this._battleId = v; break;
			case E_ArenaRecord.TIME: this._time = v; break;
			case E_ArenaRecord.ENEMY_TYPE: this._enemyType = v; break;
			case E_ArenaRecord.WIN_CAMP: this._winCamp = v; break;
			case E_ArenaRecord.LEFT_PLAYER: this._leftPlayer = v; break;
			case E_ArenaRecord.RIGHT_PLAYER: this._rightPlayer = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//战斗id
		this._battleId = 0;
		//挑战时间
		this._time = 0;
		//战斗类型（玩家，关卡，机器人等）
		this._enemyType = 0;
		//胜利方
		this._winCamp = 0;
		//左边玩家
		if (this._leftPlayer) {
			this._leftPlayer.destroy();
			this._leftPlayer = null;
		}
		if (!fromDestroy) {
			this._leftPlayer = ArenaRecordPlayer.create();
		}
		//右边玩家
		if (this._rightPlayer) {
			this._rightPlayer.destroy();
			this._rightPlayer = null;
		}
		if (!fromDestroy) {
			this._rightPlayer = ArenaRecordPlayer.create();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._battleId) {
			json.battleId = this._battleId;
		}
		if (this._time) {
			json.time = this._time;
		}
		if (this._enemyType) {
			json.enemyType = this._enemyType;
		}
		if (this._winCamp) {
			json.winCamp = this._winCamp;
		}
		if (this._leftPlayer) {
			json.leftPlayer = this._leftPlayer.stringify(false);
		}
		if (this._rightPlayer) {
			json.rightPlayer = this._rightPlayer.stringify(false);
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.battleId) {
			this._battleId = json.battleId;
		}
		if (json.time) {
			this._time = json.time;
		}
		if (json.enemyType) {
			this._enemyType = json.enemyType;
		}
		if (json.winCamp) {
			this._winCamp = json.winCamp;
		}
		if (json.leftPlayer) {
			this._leftPlayer.destroy();
			this._leftPlayer = ArenaRecordPlayer.create(json.leftPlayer);
		}
		if (json.rightPlayer) {
			this._rightPlayer.destroy();
			this._rightPlayer = ArenaRecordPlayer.create(json.rightPlayer);
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeLongNumber(this._battleId);
		byte.writeLongNumber(this._time);
		byte.writeUint8(this._enemyType);
		byte.writeUint8(this._winCamp);
		this._leftPlayer.toBytes(byte);
		this._rightPlayer.toBytes(byte);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._battleId = byte.readLongNumber();
		this._time = byte.readLongNumber();
		this._enemyType = byte.readUint8();
		this._winCamp = byte.readUint8();
		this._leftPlayer.fromBytes(byte);
		this._rightPlayer.fromBytes(byte);
		return this;
	}


	/**克隆*/
	public clone(): ArenaRecord {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ArenaRecord.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ArenaRecord.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//战斗id
			if (idx === E_ArenaRecord.BATTLE_ID) {
				const oldv = this._battleId;
				this._battleId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._battleId, oldv);
				i += 2;
				continue;
			}
			//挑战时间
			if (idx === E_ArenaRecord.TIME) {
				const oldv = this._time;
				this._time = us[i + 1];
				IAsync.dispatch(eventID, idx, this._time, oldv);
				i += 2;
				continue;
			}
			//战斗类型（玩家，关卡，机器人等）
			if (idx === E_ArenaRecord.ENEMY_TYPE) {
				const oldv = this._enemyType;
				this._enemyType = us[i + 1];
				IAsync.dispatch(eventID, idx, this._enemyType, oldv);
				i += 2;
				continue;
			}
			//胜利方
			if (idx === E_ArenaRecord.WIN_CAMP) {
				const oldv = this._winCamp;
				this._winCamp = us[i + 1];
				IAsync.dispatch(eventID, idx, this._winCamp, oldv);
				i += 2;
				continue;
			}
			//左边玩家
			if (idx === E_ArenaRecord.LEFT_PLAYER) {
				const fui: string = us[i + 1];
				if (this._leftPlayer) {
					this._leftPlayer.processUpdate(fui);
				}
				else {
					console.error('ArenaRecord leftPlayer is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}
			//右边玩家
			if (idx === E_ArenaRecord.RIGHT_PLAYER) {
				const fui: string = us[i + 1];
				if (this._rightPlayer) {
					this._rightPlayer.processUpdate(fui);
				}
				else {
					console.error('ArenaRecord rightPlayer is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in ArenaRecord with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ArenaRecord): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._battleId !== other._battleId) {
			updates.push(E_ArenaRecord.BATTLE_ID, this._battleId);
		}
		if (this._time !== other._time) {
			updates.push(E_ArenaRecord.TIME, this._time);
		}
		if (this._enemyType !== other._enemyType) {
			updates.push(E_ArenaRecord.ENEMY_TYPE, this._enemyType);
		}
		if (this._winCamp !== other._winCamp) {
			updates.push(E_ArenaRecord.WIN_CAMP, this._winCamp);
		}
		//左边玩家
		{
			const ui = this._leftPlayer.getCompareInfo(other._leftPlayer);
			if (ui && ui.length > 0) {
				updates.push(E_ArenaRecord.LEFT_PLAYER, ui);
			}
		}
		//右边玩家
		{
			const ui = this._rightPlayer.getCompareInfo(other._rightPlayer);
			if (ui && ui.length > 0) {
				updates.push(E_ArenaRecord.RIGHT_PLAYER, ui);
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ArenaRecord.TOTAL_EVENT_ID, this.getV(0));
	}

}
